package com.easy.common.util;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.*;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

//阿里云
public class ImageUtil {
    private static String ENDPOINT="oss-cn-shanghai.aliyuncs.com";
    private static final String BUCKET_NAME="pet-adopt-and-foster";
    private static final String ACCESS_KEY_ID="LTAI5tPXvEPGvbUY7Pmi1cn1";
    private static final String ACCESS_KEY_SECRET="Xw2mq0Aqbg7WFR7HL6vAaBt060r9Iu";

    private static final OSS ossClient = new OSSClientBuilder().build("http://"+ENDPOINT, ACCESS_KEY_ID, ACCESS_KEY_SECRET);
    //文件上传
    public static String upload(InputStream is, String fileName) throws Exception{
        //创建OSSClient实例
        String newFileName = UUID.randomUUID().toString() + "-" + fileName.substring(fileName.lastIndexOf("."));
        //创建OSSClient实例
        //创建PutObjectRequest对象  请求对象
        PutObjectRequest request = new PutObjectRequest(BUCKET_NAME, newFileName, is);
        //上传文件   发送请求  响应对象
        PutObjectResult result = ossClient.putObject(request);

        return "https://"+BUCKET_NAME+"."+ENDPOINT+"/"+newFileName;
    }
    //多余文件的删除   判断上传的文件和页面的文件的差集，把多余的文件删除  该方法实现先把文件都获得出来
    public static List<String> getFileList(){
        List<String> list=new ArrayList<>();//创建集合
        ListObjectsRequest request = new ListObjectsRequest(BUCKET_NAME);//创建请求对象 获取文件请求对象
        request.setMarker(null);//设置起始位置
        request.setMaxKeys(1000);//设置最大个数  最多查出多少条来
        ObjectListing objectListing= ossClient.listObjects(request); //获取文件列表
        for (OSSObjectSummary objectSummary : objectListing.getObjectSummaries()) {//遍历文件列表
            list.add(objectSummary.getKey());//获取文件名,然后添加到list中去
        }
        return list;
    }
    //删除一个文件的方法
    public static void delete(String fileName){
        ossClient.deleteObject(BUCKET_NAME,fileName);
    }
    //删除多个文件的方法
    public static void deleteList(List<String> fileNameList){
        DeleteObjectsRequest deleteObjectsRequest=new DeleteObjectsRequest(BUCKET_NAME);//创建删除多个文件的请求对象
        deleteObjectsRequest.setKeys(fileNameList);//设置文件名
        ossClient.deleteObjects(deleteObjectsRequest);//删除多个文件
    }
    //测试删除多余文件的方法
    public static void main(String[] args) {
        System.out.println(getFileList());
    }
    //测试上传图片的方法
//    public static void main(String[] args) {
//        try {
//            File file = new File("D:\\abc.jpg");
//            InputStream is = new FileInputStream( file);
//            String newFileName =upload(is,file.getName());
//            System.out.println(newFileName);
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//    }
}


































